package com.py.custom.common.web.valid.constraint;

import com.py.custom.common.web.utils.ApplicationContextUtils;
import com.py.custom.common.web.valid.CustomValidHandler;
import com.py.custom.common.web.valid.annotation.CustomValid;
import lombok.SneakyThrows;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Optional;

/**
 * description： 自定义参数校验类
 *
 * @author pengyou
 * @version 1.0.0
 * @date 2021/10/23
 */
public class CustomValidConstraint implements ConstraintValidator<CustomValid, Object> {

    private CustomValid customValid;

    @Override
    public void initialize(CustomValid customValid) {
        this.customValid = customValid;
    }

    /**
     * @param value   校验的值
     * @param context
     * @return true表示校验成功
     */
    @SneakyThrows
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value != null) {
            Class<? extends CustomValidHandler<?>> handler = customValid.handler();
            CustomValidHandler<Object> customValidHandler
                    = (CustomValidHandler<Object>) ApplicationContextUtils.getBean(handler);
            return Optional.ofNullable(customValidHandler)
                    .map(func -> customValidHandler.valid(customValid, value))
                    .orElse(false);
        }
        return true;
    }
}
